package com.iyunwen.datatool.utils;

import com.iyunwen.datatool.model.dbdo.EventDataDO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @description: excel工具类
 * @author: wangyu
 * @create: 2020-03-20 17:19
 */
public class ExcelUtils {

    /**
     * 生成Excel并写入数据信息
     *
     * @param tableDataList 数据列表
     * @return 写入数据后的工作簿对象
     */
    public static Workbook exportData(List<EventDataDO> tableDataList, List<List<EventDataDO>> sourceEventData, List<String> cellHead) {
        // 生成xlsx的Excel
        Workbook workbook = new SXSSFWorkbook();

        // 如需生成xls的Excel，请使用下面的工作簿对象，注意后续输出时文件后缀名也需更改为xls
        //Workbook workbook = new HSSFWorkbook();

        //黄色行样式
        CellStyle yellowCellStyle = workbook.createCellStyle();
        yellowCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        yellowCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //红色行样式
        CellStyle redCellStyle = workbook.createCellStyle();
        redCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
        redCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //默认行样式
        CellStyle defaultCellStyle = workbook.createCellStyle();

        // 生成Sheet表，写入第一行的列头
        Sheet sheet = buildDataSheet(workbook, cellHead, "sheet1");
        //构建每行的数据内容
        int rowNum = 1;
        for (Iterator<EventDataDO> it = tableDataList.iterator(); it.hasNext(); ) {
            EventDataDO data = it.next();
            if (data == null) {
                continue;
            }
            //输出行数据
            Row row = sheet.createRow(rowNum++);

            CellStyle cellStyle = null;
            if ("#ffff7f".equalsIgnoreCase(data.getBackgroundColor())) {
                cellStyle = yellowCellStyle;
            } else if ("#ff0000".equalsIgnoreCase(data.getBackgroundColor())) {
                cellStyle = redCellStyle;
            } else {
                cellStyle = defaultCellStyle;
            }
            convertDataToRow(data, row, cellStyle);
        }

        int index = 0;
        for (List<EventDataDO> sourceEventDatum : sourceEventData) {
            index++;
            Sheet sourceEventDataSheet = buildDataSheet(workbook, cellHead, "原始数据" + index);
            //构建每行的数据内容
            int sourceEventDataSheetRowNum = 1;
            for (Iterator<EventDataDO> it = sourceEventDatum.iterator(); it.hasNext(); ) {
                EventDataDO data = it.next();
                if (data == null) {
                    continue;
                }
                //输出行数据
                Row row = sourceEventDataSheet.createRow(sourceEventDataSheetRowNum++);

                CellStyle cellStyle = null;
                if ("#ffff7f".equalsIgnoreCase(data.getBackgroundColor())) {
                    cellStyle = yellowCellStyle;
                } else if ("#ff0000".equalsIgnoreCase(data.getBackgroundColor())) {
                    cellStyle = redCellStyle;
                } else {
                    cellStyle = defaultCellStyle;
                }
                convertDataToRow(data, row, cellStyle);
            }
        }

        return workbook;
    }

    /**
     * 生成sheet表，并写入第一行数据（列头）
     *
     * @param workbook 工作簿对象
     * @return 已经写入列头的Sheet
     */
    private static Sheet buildDataSheet(Workbook workbook, List<String> cellHead, String name) {
        Sheet sheet = workbook.createSheet(name);
        // 设置列头宽度
        for (int i = 0; i < cellHead.size(); i++) {
            sheet.setColumnWidth(i, 4000);
        }
        // 设置默认行高
        sheet.setDefaultRowHeight((short) 400);
        // 构建头单元格样式
        CellStyle cellStyle = buildHeadCellStyle(sheet.getWorkbook());
        // 写入第一行各列的数据
        Row head = sheet.createRow(0);
        for (int i = 0; i < cellHead.size(); i++) {
            Cell cell = head.createCell(i);
            cell.setCellValue(cellHead.get(i));
            cell.setCellStyle(cellStyle);
        }
        return sheet;
    }

    /**
     * 设置第一行列头的样式
     *
     * @param workbook 工作簿对象
     * @return 单元格样式对象
     */
    private static CellStyle buildHeadCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        //对齐方式设置
        style.setAlignment(HorizontalAlignment.CENTER);
        //边框颜色和宽度设置
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 下边框
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 左边框
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 右边框
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 上边框
        //设置背景颜色
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //粗体字设置
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        return style;
    }

    /**
     * 将数据转换成行
     *
     * @param data 源数据
     * @param row  行对象
     * @return
     */
    private static void convertDataToRow(EventDataDO data, Row row, CellStyle cellStyle) {
        int cellNum = 0;
        Cell cell;
        // 标记
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getEventRemark() ? "" : data.getEventRemark());

        // 事件时标
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);

        if (0 != data.getEventTime()) {
            Date eventTimeDate = new Date(data.getEventTime());
            String eventTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(eventTimeDate);
            cell.setCellValue(eventTime);
        } else {
            cell.setCellValue("");
        }
        // 类型
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getEventType() ? "" : data.getEventType());
        // 主从
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getMasterOrSlave() ? "" : data.getMasterOrSlave());
        // 事件号
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getEventNumber() ? "" : data.getEventNumber());
        // 事件来源
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getEventSource() ? "" : data.getEventSource());
        // 事件描述
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getEventDesc() ? "" : data.getEventDesc());
        // 事件等级
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getEventLevel() ? "" : data.getEventLevel());
        // 状态
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getEventStatus() ? "" : data.getEventStatus());
        // 持续时间
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getDuration() ? "" : data.getDuration());
        // 设备描述
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getDeviceDescription() ? "" : data.getDeviceDescription());
        // 操作者
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getOperator() ? "" : data.getOperator());
        // 确认人
        cell = row.createCell(cellNum++);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(null == data.getConformPerson() ? "" : data.getConformPerson());
    }
}
